package com.news.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.news.entity.User;
import com.news.service.UserService;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		//获取数据库字段的两种方式：1、通过字段名			
		if(username != null && password != null){
			UserService uService = new UserService();
			User user = uService.queryUser(username, password);
			HttpSession session=request.getSession();
			session.setAttribute("username", user.getUsername());
			session.setAttribute("password", user.getPassword());
			session.setAttribute("role", user.getRole());
			session.setAttribute("sex", user.getSex());
			session.setAttribute("age", user.getAge());
			session.setAttribute("user_id", user.getId());
			System.out.println("role"+user.getRole());
			if(user != null){
				request.getSession().setAttribute("currentUser",user);
				if(user.getRole().equals("0")){
					request.getRequestDispatcher("/jsp/main_admin.jsp").forward(request, response);
				}else{
					request.getRequestDispatcher("/jsp/main_user.jsp").forward(request, response);
				}		
			}
		}else{
			System.out.println("wwwww");
			response.setContentType("text/html; charset=UTF-8");
			response.getWriter().print("<script> alert(\"登录失败!\"); </script>");
			response.setHeader("refresh", "0.2;url=jsp/login.jsp");
//			response.sendRedirect(request.getContextPath() + "/jsp/login.jsp");
			System.out.println(request.getContextPath() + "/jsp/login.jsp");
		}
	}

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
}
